<template>
  <el-container class="documentIpt_all">
    <el-header class="documentIpt_header" height="150px">
      <el-alert title="请您先选择知识点并生成题目后，再进行组卷！" type="warning" show-icon />
      <p :class="{ shifted: drawerVisible }">大模型出题组卷</p>
      <!-- <el-button
        size="large"
        type="primary"
        class="documentIpt_btn"
        @click="
          drawerVisible = true;
          bool = false;
        ">
        <span class="long-arrow-left">←|</span>
      </el-button> -->
      <div class="doc_btn_box">
        <el-button size="medium" type="primary" plain style="
            width: 150px;
            height: 36px;
            font-size: 14px;
            margin-bottom: 15px;
            color: #222;
          " @click="drawerVisible = true; bool = false;"><img src="@/assets/images/ct.png"
            class="btn_icon" />出题</el-button>
        <el-button size="medium" type="primary" plain style="
            width: 150px;
            height: 36px;
            font-size: 14px;
            margin-bottom: 15px;
            margin-left: 20px;
            color: #222;
          " @click="goToZujuan"><img src="@/assets/images/zj.png" class="btn_icon" />组卷</el-button>
      </div>
    </el-header>

    <el-main class="documentIpt_main">

      <el-table :style="tableWidthStyle" empty-text="没有数据" :data="chapters">
        <el-table-column prop="title" label="章节">
          <template v-slot:default="{ row }">
            <div class="topic-container">
              <h3 class="knowledge-title" @click="showTopic(row)">{{ row.title }}
                <span style="font-size: 12px; color:#aaa">点击此处可收放内容</span>
              </h3>
              <el-checkbox v-model="row.allChecked" @change="toggleAllCheckboxes(row)">全选</el-checkbox>
              <!-- 2025/04/06修改，用于初始展开所有选项 -->
              <!-- <ul v-if="row.expanded"> -->
              <ul v-if="!row.expanded">
                <li v-for="con in row.content" :key="con.point" class="knowledge-cont">
                  <!-- 添加勾选框 -->
                  <el-checkbox v-model="con.isChecked" @change="handleCheckboxChange(row, con)"></el-checkbox>
                  {{ con.point }}
                </li>
              </ul>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 文档内容抽屉 -->
      <div class="side-panel" :class="{ active: drawerVisible }">
        <div class="title-container" style="position: sticky; top: 0">
          <h2 class="title">文件预览</h2>
          <el-button class="close-btn" @click="handleClose">
            <el-icon class="el-icon--close" style="color: #fff; position: absolute; top: 0; right: 10px">×</el-icon>
          </el-button>
        </div>
        <div style="height: calc(100% - 150px); overflow-y: auto;padding:10px;box-sizing:border-box;">
          <div v-if="selectedContent.length">
            <p v-for="(item, index) in selectedContent" :key="index + 'sc'" style="line-height:28px;">
              {{ item.summary }}
            </p>
          </div>
          <div v-if="fileContent" class="file-content">
            <pre class="auto-wrap">{{ fileContent }}</pre>
          </div>
        </div>

        <div class="drawer-footer">
          <div class="choices">
            <el-select v-model="questionType" placeholder="请选择题型" style="box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.3)">
              <el-option v-for="item in questionsTypeOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <el-select v-model="generateMode" placeholder="请选择生成方式" style="box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.3)">
              <el-option v-for="item in generateModeOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <el-select v-model="difficultyLevel" collapse-tags style="box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.3)"
              placeholder="请选择难度等级">
              <el-option v-for="item in difficultyLevelOptions" :key="item.value" :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div class="buttons-container">
            <el-button size="medium" type="primary" class="documentIpt_btn" @click="generateQuestions"
              v-loading="btnLoading" :disabled="isDisabled">生成题目</el-button>
            <el-button size="medium" type="warning" class="save_btn" @click="saveAndClose"
              :disabled="isDisabled">保存</el-button>
          </div>
          <!-- 提示信息 -->
          <el-alert v-if="showSuccessMessage" type="success" :closable="false" style="display: inline-block">
            传输成功
          </el-alert>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script lang="ts">
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import { Ref, computed, reactive, ref, watch } from "vue";
import { ElMessage, genFileId, UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import { Document, UploadFilled } from "@element-plus/icons-vue";
import PageResult from "@/views/PageResult.vue";

//知识点内容
interface Con {
  point: string;
  text: string;
  isChecked: Boolean
}
//章节
interface Chapter {
  content: Con[];
  title: string;
  allChecked: boolean; // 新增全选状态字段
}

interface uploadCon {
  summary: string;
  content: string;
}

// 定义 jsonData 的类型
type JsonData = Chapter[];
export default {
  name: "page2",
  components: { UploadFilled },
  setup() {
    const { useStore } = require("../store/index.js");
    const store = useStore();
    const router = useRouter();
    const route = useRoute();
    const btnLoading = ref(false)

    // 使用 ref 定义单个响应式变量
    const showSuccessMessage = ref(false);
    // 使用 reactive 定义对象或数组等复杂响应式数据
    const questionsTypeOptions = reactive([
      { value: "choice", label: "单选题" },
      // { value: "multi_choose", label: "多选题" },
      { value: "TF", label: "判断题" },
      { value: "fill", label: "填空题" },
      { value: "answer", label: "简答题" }
    ]);

    const generateModeOptions = reactive([
      { value: "text", label: "根据教材内容生成" },
      { value: "open", label: "开放式生成" },
    ]);

    const difficultyLevelOptions = reactive([
      { value: "easy", label: "简单" },
      //{ value: "中等", label: "中等" },
      { value: "difficulty", label: "困难" },
    ]);

    // 使用 ref 定义单个响应式变量
    const questionType = ref("");
    const difficultyLevel = ref("");
    const generateMode = ref("");

    // 若上面三个变量有一个为空，则禁用生成题目按钮
    const isDisabled = computed(() => {
      return !questionType.value || !difficultyLevel.value || !generateMode.value;
    });

    const drawerVisible = ref(true);
    const fileContent = ref();
    const jsonData = ref<JsonData>([]);
    const bool = ref(true); // 初始条件，可以根据需要修改
    const toggleAllCheckboxes = (row: Chapter) => {
      // 切换所有子项的选中状态
      row.content.forEach(con => {
        con.isChecked = row.allChecked;
      });
      // 更新 selectedContent
      updateSelectedContent(row);
    };


    const updateSelectedContent = (row: Chapter) => {
      // 移除当前章节原有的选中项
      selectedContent.value = selectedContent.value.filter(
        item => !row.content.some(c => c.point === item.summary)
      );
      // 添加新选中的项
      row.content
        .filter(con => con.isChecked)
        .forEach(con => {
          selectedContent.value.push({
            summary: con.point,
            content: con.text || '', // 确保 content 不为 undefined
          });
        });
    };
    // 计算表格宽度样式
    const tableWidthStyle = computed(() => ({
      width: bool.value ? "100%" : "60%",
      "text-align": "center",
      // marginLeft: '20px', // 设置左侧外边距为20px
      // marginRight: '20px', // 设置左侧外边距为20px
      borderRadius: "10px",
    }));
    const goToSearchPage = function () {
      router.push({
        name: "Home",
      });
    };

    let courseId = ref(route.query.courseId || localStorage.getItem('courseId'))
    if (courseId.value) {
      localStorage.setItem('courseId', `${courseId.value}`)
    }
    let courseName = ref(route.query.courseName || localStorage.getItem('courseName'))
    if (courseName.value) {
      localStorage.setItem('courseName', `${courseName.value}`)
    }

    const getKnowledge = function () {
      axios.get(`${store.apiBaseURI}/get_knowledge?course_id=${courseId.value}`)
        .then((res) => {
          if (res.data.status == false) {
            ElMessage.error(res.data.msg);
          } else {
            let arr: any = []

            arr = res.data.flat().reduce((acc: any, curr: any) => {
              if (!acc.find((item: any) => item.title.replaceAll(' ', '') == curr.title.replaceAll(' ', ''))) {
                acc.push(curr);
              }
              return acc;
            }, []);

            jsonData.value = arr
            localStorage.setItem('chap', JSON.stringify(jsonData.value))
            jsonData.value = JSON.parse(localStorage.getItem('chap') || '[]').map((chapter: Chapter) => ({
              ...chapter,
              allChecked: false, // 默认未全选
            }));
          }
        }).catch((error) => {
          console.error(error);
          ElMessage.error("知识点获取失败！");
        });
    }

    watch([route], ([nRoute], [pRoute]) => {
      courseId.value = route.query.courseId ? route.query.courseId : localStorage.getItem('courseId')
      courseName.value = route.query.courseName ? route.query.courseName : localStorage.getItem('courseName')
      // const chap = localStorage.getItem('chap') || "[]";
      // jsonData.value = JSON.parse(chap);
      getKnowledge();
    })

    getKnowledge()

    const goToZujuan = function () {
      store.text = "组卷";
      router.push({
        name: "zujuan",
        query: { courseId: courseId.value, courseName: courseName.value, random: (Math.random() * 1000).toFixed(0) }
      });
    };

    const generateQuestions = () => {
      if (selectedContent.value.length == 0) {
        ElMessage.error("未选择知识点！");
        return
      }
      // 自定义上传行为
      btnLoading.value = true
      axios
        .post(`${store.apiBaseURI}/text_generate_question`, {
          questionType: questionType.value,
          generateMode: generateMode.value,
          difficultyLevel: difficultyLevel.value,
          data: selectedContent.value,
          course_id: courseId.value
        }, { timeout: 600000 })
        .then((response) => {
          // 确保response.status是200，即请求成功
          if (response.status !== 200) {
            throw new Error("Network response was not ok");
          }
          jsonData.value.map(item => {
            item.content.map(cItem => {
              if (cItem.isChecked) {
                cItem.isChecked = !cItem.isChecked
              }
            })
          })
          console.log("response.data", response.data);
          // 清空selectedContent（可选）
          selectedContent.value = [];
          fileContent.value = response.data;
          btnLoading.value = false
          ElMessage.success("题目生成成功！");
        })
        .catch((error) => {
          console.error(error);
          btnLoading.value = false
          ElMessage.error("题目生成失败！");
        });
    };

    // 关闭抽屉
    const handleClose = () => {
      drawerVisible.value = false;
      bool.value = true;
      // fileContent.value = '';
    };

    // 第一次赋值
    // const chap = localStorage.getItem('chap') || "[]";
    // jsonData.value = JSON.parse(chap);
    // 处理数据
    const chapters = computed(() => {
      if (jsonData.value && jsonData.value.length > 0) {
        return jsonData.value;
      }
      // 如果没有数据，可以返回一个空数组或其他默认值
      return [];
    });
    const showTopic = (row: { expanded: boolean }) => {
      row.expanded = !row.expanded;
    };

    // 选中与取消选中知识点
    const selectedContent: Ref<uploadCon[]> = ref([]); // 用于存储选中的知识点
    const handleCheckboxChange = (
      chapter: Chapter,
      con: Con & {
        isChecked: boolean;
      }
    ) => {
      drawerVisible.value = true;
      bool.value = false;
      fileContent.value = "";
      if (con.isChecked) {
        // 如果知识点被选中，则添加到selectedContent数组中
        selectedContent.value.push({
          summary: con.point,
          content: con.text,
        });
        // console.log('selectedContentselectedContent@@',selectedContent.value)
      } else {
        // 如果知识点被取消选中，则从selectedContent数组中移除
        const index = selectedContent.value.findIndex((item) => item.summary === con.point);
        if (index !== -1) {
          selectedContent.value.splice(index, 1);
          // console.log('selectedContentselectedContent@@',selectedContent.value)
        }
      }
    };
    const saveAndClose = () => {
      window.parent.postMessage({ closeIframe: true }, '*')
    }

    return {
      isDisabled,
      store,
      questionsTypeOptions,
      generateModeOptions,
      difficultyLevelOptions,
      questionType,
      generateMode,
      difficultyLevel,
      showSuccessMessage,
      goToSearchPage,
      generateQuestions,
      drawerVisible,
      fileContent,
      handleClose,
      chapters,
      showTopic,
      tableWidthStyle,
      bool,
      handleCheckboxChange,
      selectedContent,
      goToZujuan,
      btnLoading,
      saveAndClose,
      toggleAllCheckboxes
    };
  },
};
</script>
<style lang="less" scoped>
.documentIpt_all {
  height: 100vh;
  background-image: url(../assets/main_bg.jpg);
  background-size: cover;
}

.documentIpt_header {
  padding: 0;
  background-size: cover;
  position: relative;

  p {
    position: absolute;
    top: 40px;
    left: 50%;
    transform: translateX(-50%);
    color: #304156;
    font-weight: 700;
    font-size: 35px;
  }

  p.shifted {
    transform: translateX(-500px);
    /* 原页面内容左移 */
    transition: transform 0.3s;
    /* 平滑过渡效果 */
  }

  .p_bottom {
    position: absolute;
    top: 110px;
    left: 50%;
    transform: translateX(-50%);

    /deep/ .el-breadcrumb__item>span {
      color: #ffffff;
      font-size: 15px;
      font-weight: normal;
    }
  }

  .p_bottom.shifted {
    transform: translateX(-480px);
    /* 原页面内容左移 */
    transition: transform 0.3s;
    /* 平滑过渡效果 */
  }

  .long-arrow-left {
    font-size: 24px;
    /* 设置字体大小 */
    font-weight: bold;
    /* 设置字体加粗 */
    margin-left: 5px;
    color: #409eff;
  }

  .documentIpt_btn {
    position: absolute;
    top: 100px;
    /* 相对于页面的右上角定位 */
    right: -5px;
    /* 相对于页面的右上角定位 */
    background-color: transparent;
    /* 清除背景色 */
    border: none;
    /* 清除边框 */
    color: #fff;
    /* 设置文字颜色 */
    text-align: center;
    cursor: pointer;
  }
}

.doc_btn_box {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 1%;

  .btn_icon {
    width: 16px;
    height: 16px;
    margin-right: 15px;
  }

  ::v-deep .el-button:focus,
  .el-button:hover {
    background-color: #f0f8ff !important;
  }
}

.documentIpt_main {
  width: 98%;
  margin: 0 auto;
  padding: 0;
  height: 495px;
  position: relative;

  .left {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    width: 750px;
    height: 220px;
    background-color: #b49c73;
    border-radius: 5px;

    .upload {
      position: absolute;
      top: 20px;
      left: 50%;
      transform: translateX(-50%);
      width: 700px;
      height: 180px;
      padding: 10px;
    }

    .buttons-container {
      display: flex;
      justify-content: center;
      gap: 200px;
      /* 添加按钮之间的间距 */
    }

    //.documentIpt_btn {
    //  //margin-right: 300px;
    //  //margin-top: 300px;
    //  width: 100px;
    //  height: 50px;
    //  background-color: wheat;
    //  border-color:wheat;
    //  color: black;
    //  font-size: 20px;
    //  font-weight: 800;
    //}
  }

  .side-panel {
    position: fixed;
    top: 5px;
    right: -100%;
    bottom: 0;
    width: 700px;
    background: #f9f9f9;
    z-index: 2;
    overflow-y: auto;
    transition: right 0.3s;
    border: 1px solid #eaeaea;
    /* 添加边框 */
    box-shadow: -5px 0 5px rgba(0, 0, 0, 0.2);
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;

    .choices {
      display: flex;
      justify-content: center;
      gap: 20px;
    }
  }

  .drawer-footer {
    width: 100%;
    height: 100px;
  }

  .title-container {
    padding: 0;
    background: #409eff;
    /* 标题背景色 */
    border-bottom: 1px solid #eaeaea;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    display: flex;
    /* 使容器变为flex布局 */
  }

  .title {
    font-size: 20px;
    font-weight: bold;
    margin: 0;
    color: white;
    padding: 10px;
  }

  .side-panel.active {
    right: 0;
    /* 显示侧边面板 */
  }

  .file-content {
    padding: 20px;
    word-wrap: break-word;
    /* 允许长单词换行 */
    white-space: pre-wrap;
    /* 保持换行和空格 */
    height: 300px;
    /* 设置一个最小高度，以便内容能够显示 */
  }

  .auto-wrap {
    /* 强制内容在边界内换行 */
    word-wrap: break-word;
    /* 防止内容溢出容器 */
    overflow-wrap: break-word;
    white-space: pre-wrap;
    /* 保留空格和换行符，同时允许内容在边界内换行 */
  }

  .close-btn {
    display: block;
    width: 81%;
    padding: 0;
    background-color: transparent;
    /* 清除背景色 */
    border: none;
    /* 清除边框 */
    color: #fff;
    /* 设置关闭按钮文字颜色 */
    text-align: center;
    cursor: pointer;
  }

  /* 移除点击时的背景颜色变化效果 */
  .close-btn:hover {
    background-color: transparent;
  }

  .close-btn .el-icon--close {
    position: absolute;
    top: 0;
    right: 10px;
    font-size: 40px;
    /* 调整图标大小 */
    cursor: pointer;
  }

  .left.shifted {
    transform: translateX(-650px);
    /* 原页面内容左移 */
    transition: transform 0.3s;
    /* 平滑过渡效果 */
  }

  .buttons-container {
    display: flex;
    justify-content: center;
    //gap: 200px; /* 添加按钮之间的间距 */
  }

  .documentIpt_btn {
    margin-top: 20px;
    width: 200px;
    height: 38px;
    font-size: 15px;
  }

  .save_btn {
    width: 80px;
    height: 38px;
    font-size: 15px;
    margin-top: 20px;
    margin-left: 30px;
  }
}

::v-deep .el-loading-spinner {
  width: 100% !important;
  height: 50px !important;
  /*这个是自己想设置的 gif 加载动图*/
  background-image: url('@/assets/loading2.gif') !important;
  background-repeat: no-repeat !important;
  background-size: 50px 50px !important;
  background-position: center;
  /*覆盖 element-ui  默认的 50%    因为此处设置了height:100%,所以不设置的话，会只显示一半，因为被top顶下去了*/
  position: relative;
  /* 设置相对定位 */
}
</style>
